<style scoped>
/* 彻底修复滚动问题 */
html, body {
  height: 100%;
  overflow: auto;
}

.page-container {
  min-height: 100vh;
  width: 100%;
  overflow-y: visible;
  padding-bottom: 4rem;
  position: relative;
}

.main-content {
  padding-bottom: 80px;
}

/* 卡片样式 */
.card {
  font-family: 'Monaco', 'Menlo', monospace;
  display: inline-flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 55px;
  border-radius: 4px;
  margin: 4px;
  font-weight: bold;
  user-select: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  line-height: 1.2;
}

/* 花色符号样式 */
.card span {
  text-align: center;
}

/* 花色颜色 */
.spade, .club {
  color: #000;
}
.heart, .diamond {
  color: #e74c3c;
}

/* 背景色 */
.card-bg {
  background-color: #fff;
  border: 1px solid #ddd;
}

/* 路图样式 */
.road-map-container {
  width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
  padding: 16px;
  border: 1px solid #eaeaea;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}

.road-column {
  min-width: 74px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.road-column:not(:last-child)::after {
  content: "";
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  border-right: 1px dashed rgba(0, 0, 0, 0.1);
}

.line-height-1 {
  line-height: 1.1;
}

/* 增加淡色背景网格效果 */
.road-map-container {
  background-image: 
    linear-gradient(rgba(200, 200, 200, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(200, 200, 200, 0.1) 1px, transparent 1px);
  background-size: 74px 74px;
}

/* 适配移动端的路图样式 */
@media (max-width: 640px) {
  .w-16 {
    width: 3rem !important;
  }
  
  .h-16 {
    height: 3rem !important;
  }
  
  .road-column {
    min-width: 55px;
  }
}
</style>

<template>
  <div class="page-container bg-gradient-to-br from-blue-100 via-gray-100 to-pink-100">
    <div class="container mx-auto px-4 py-8 pb-24 main-content">
      <div class="flex items-center justify-between mb-6">
        <h1 class="text-3xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-blue-500 to-pink-500">
          模拟结果详情
        </h1>
        <div class="flex space-x-3">
          <button 
            @click="clearSimulation"
            class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
          >
            删除此模拟记录
          </button>
          <button 
            @click="$router.push('/results')"
            class="px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
          >
            返回结果列表
          </button>
        </div>
      </div>
      
      <div v-if="isLoading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
      </div>
      
      <div v-else-if="error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
        <strong class="font-bold">错误！</strong>
        <span class="block sm:inline">{{ error }}</span>
      </div>
      
      <div v-else>
        <!-- 牌组数据显示 -->
        <div v-if="deckInfo && deckInfo.deck_data" class="bg-white rounded-xl shadow-md p-6 mb-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-gray-800">牌组数据 (种子: {{ deckInfo.deck_seed }})</h2>
            <div class="flex items-center space-x-2">
              <button 
                @click="showAllCards = !showAllCards" 
                class="px-2 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors text-sm"
              >
                {{ showAllCards ? '收起' : '显示全部牌' }}
              </button>
            </div>
          </div>
          
          <div v-if="!showAllCards" class="text-gray-600 mb-4">
            <p>点击"显示全部牌"按钮可查看完整牌组 (共{{ deckInfo.deck_data.length }}张)</p>
          </div>
          
          <div v-else class="overflow-x-auto mb-4">
            <div class="flex flex-wrap">
              <div v-for="(card, index) in deckInfo.deck_data" :key="index" class="card card-bg" :class="getCardClass(card)">
                <span v-html="getCardDisplay(card)"></span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 模拟概要 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
          <h2 class="text-xl font-bold text-gray-800 mb-4">模拟概要</h2>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="text-sm font-medium text-gray-500">策略名称</h3>
              <p class="text-lg font-bold text-gray-800">{{ summary.strategy_name }}</p>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="text-sm font-medium text-gray-500">总局数</h3>
              <p class="text-lg font-bold text-gray-800">{{ summary.total_rounds }}</p>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="text-sm font-medium text-gray-500">盈亏</h3>
              <p class="text-lg font-bold" :class="summary.net_profit > 0 ? 'text-green-600' : 'text-red-500'">
                {{ summary.net_profit > 0 ? '+' : '' }}{{ summary.net_profit }}
              </p>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="text-sm font-medium text-gray-500">主打方向</h3>
              <p class="text-lg font-bold text-gray-800">
                {{ summary.main_choice === 'player' ? '闲' : (summary.main_choice === 'banker' ? '庄' : '未确定') }}
              </p>
            </div>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="text-sm font-medium text-gray-500">胜局 / 败局</h3>
              <p class="text-lg font-bold text-gray-800">
                {{ summary.win_rounds }} / {{ summary.lose_rounds }}
                <span class="text-sm font-normal text-gray-500 ml-1">
                  (胜率: {{ ((summary.win_rounds / (summary.win_rounds + summary.lose_rounds)) * 100).toFixed(1) }}%)
                </span>
              </p>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="text-sm font-medium text-gray-500">跳过局数</h3>
              <p class="text-lg font-bold text-gray-800">
                {{ summary.total_rounds - summary.win_rounds - summary.lose_rounds }}
              </p>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg">
              <h3 class="text-sm font-medium text-gray-500">每局平均收益</h3>
              <p class="text-lg font-bold" :class="avgProfit > 0 ? 'text-green-600' : 'text-red-500'">
                {{ avgProfit > 0 ? '+' : '' }}{{ avgProfit }}
              </p>
            </div>
          </div>
          
          <!-- 剩余牌数信息 -->
          <div class="mt-4 bg-blue-50 p-4 rounded-lg border border-blue-200">
            <h3 class="text-sm font-medium text-blue-700 mb-1">模拟结束原因</h3>
            <p class="text-gray-800">
              <span v-if="summary.remaining_cards !== undefined">
                剩余牌数: <span class="font-semibold">{{ summary.remaining_cards }}</span>张
                <span class="text-sm text-gray-600 ml-2">
                  {{ summary.remaining_cards < 104 ? '(牌不足2副，模拟自动结束)' : '(达到最大局数限制)' }}
                </span>
              </span>
              <span v-else>模拟正常结束</span>
            </p>
          </div>
        </div>
        
        <!-- 收益曲线图表 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
          <h2 class="text-xl font-bold text-gray-800 mb-4">收益曲线</h2>
          <div ref="profitChart" style="width: 100%; height: 400px; min-height: 300px;"></div>
        </div>
        
        <!-- 单局输赢分析图表 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
          <h2 class="text-xl font-bold text-gray-800 mb-4">单局输赢分析</h2>
          <div ref="roundProfitChart" style="width: 100%; height: 300px; min-height: 250px;"></div>
        </div>
        
        <!-- 胜负统计图表 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          <div class="bg-white rounded-xl shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">游戏结果分布</h2>
            <div ref="resultPieChart" style="width: 100%; height: 300px; min-height: 250px;"></div>
          </div>
          <div class="bg-white rounded-xl shadow-md p-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">下注方向统计</h2>
            <div ref="betChoiceChart" style="width: 100%; height: 300px; min-height: 250px;"></div>
          </div>
        </div>
        
        <!-- 详细轮次数据表格 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-gray-800">详细轮次数据 (共{{ rounds.length }}局)</h2>
            <div class="flex items-center space-x-2">
              <label class="text-sm text-gray-600">每页显示:</label>
              <select 
                v-model="pageSize" 
                class="p-1 border border-gray-300 rounded"
                @change="currentPage = 1"
              >
                <option :value="10">10</option>
                <option :value="20">20</option>
                <option :value="50">50</option>
                <option :value="100">100</option>
                <option :value="rounds.length">全部</option>
              </select>
            </div>
          </div>
          
          <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
              <thead class="bg-gray-50">
                <tr>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">轮次</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">下注方向</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">下注金额</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">结果</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">盈亏</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">闲牌型</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">闲点数</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">庄牌型</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">庄点数</th>
                  <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">策略备注</th>
                </tr>
              </thead>
              <tbody class="bg-white divide-y divide-gray-200">
                <tr v-for="round in paginatedRounds" :key="round.round_id" class="hover:bg-gray-50">
                  <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">{{ round.round_id }}</td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm">
                    <span v-if="round.bet_choice" :class="getBetChoiceClass(round.bet_choice)">
                      {{ round.bet_choice === 'player' ? '闲' : (round.bet_choice === 'banker' ? '庄' : '和') }}
                    </span>
                    <span v-else class="text-gray-400">未下注</span>
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">
                    {{ round.bet_amount > 0 ? round.bet_amount : '-' }}
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm">
                    <span :class="getResultClass(round.result)">
                      {{ round.result === 'player' ? '闲' : (round.result === 'banker' ? '庄' : '和') }}
                    </span>
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm font-medium" :class="getProfitClass(round)">
                    {{ round.bet_amount > 0 ? (round.win_or_lose === 1 ? '+' + round.payout : (round.win_or_lose === 0 ? '-' + round.bet_amount : '0')) : '-' }}
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm">
                    <div class="flex gap-1">
                      <span v-for="(card, idx) in round.player_hand" :key="`player-${idx}`" 
                        class="inline-flex items-center justify-center w-8 h-10 border border-gray-300 rounded" 
                        :class="getCardClassByString(card)">
                        {{ formatCard(card) }}
                      </span>
                    </div>
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{{ round.player_points }}</td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm">
                    <div class="flex gap-1">
                      <span v-for="(card, idx) in round.banker_hand" :key="`banker-${idx}`" 
                        class="inline-flex items-center justify-center w-8 h-10 border border-gray-300 rounded" 
                        :class="getCardClassByString(card)">
                        {{ formatCard(card) }}
                      </span>
                    </div>
                  </td>
                  <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500">{{ round.banker_points }}</td>
                  <td class="px-4 py-3 text-sm text-gray-500 max-w-xs truncate">{{ round.strategy_note }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 分页控制 -->
          <div v-if="totalPages > 1" class="flex justify-between items-center mt-8 sticky bottom-0 bg-white py-4 border-t">
            <div>
              <span class="text-sm text-gray-700">
                显示 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, rounds.length) }} 条，共 {{ rounds.length }} 条
              </span>
            </div>
            <div class="flex space-x-1">
              <button 
                class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 disabled:opacity-50"
                :disabled="currentPage === 1"
                @click="currentPage = 1"
              >
                首页
              </button>
              <button 
                class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 disabled:opacity-50"
                :disabled="currentPage === 1"
                @click="currentPage--"
              >
                上一页
              </button>
              <button 
                v-for="page in displayedPages" 
                :key="page"
                class="px-3 py-1 rounded"
                :class="page === currentPage ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'"
                @click="currentPage = page"
              >
                {{ page }}
              </button>
              <button 
                class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 disabled:opacity-50"
                :disabled="currentPage === totalPages"
                @click="currentPage++"
              >
                下一页
              </button>
              <button 
                class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 disabled:opacity-50"
                :disabled="currentPage === totalPages"
                @click="currentPage = totalPages"
              >
                尾页
              </button>
            </div>
          </div>
        </div>
        
        <!-- 百家乐路图显示 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-20">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-gray-800">百家乐路图</h2>
            <div class="flex flex-wrap items-center gap-4">
              <div class="flex items-center">
                <div class="w-5 h-5 rounded-full bg-red-500 mr-1"></div>
                <span class="text-sm">庄赢</span>
              </div>
              <div class="flex items-center">
                <div class="w-5 h-5 rounded-full bg-blue-500 mr-1"></div>
                <span class="text-sm">闲赢</span>
              </div>
              <div class="flex items-center">
                <div class="w-5 h-5 rounded-full bg-green-500 mr-1"></div>
                <span class="text-sm">和</span>
              </div>
              <div class="flex items-center">
                <div class="relative w-5 h-5 rounded-full bg-gray-400 mr-1">
                  <div class="absolute -right-1 -top-1 w-3 h-3 rounded-full bg-yellow-400 flex items-center justify-center">
                    <span class="text-white text-xs font-bold">↘</span>
                  </div>
                </div>
                <span class="text-sm">拐弯（在第6行向右延伸）</span>
              </div>
            </div>
          </div>
          
          <div class="overflow-x-auto">
            <div class="road-map-container" :style="{ minHeight: `${Math.min(rounds.length * 10, 500)}px` }">
              <div class="flex">
                <div v-for="(column, colIndex) in roadMap" :key="colIndex" class="road-column">
                  <template v-for="(cell, rowIndex) in column">
                    <!-- 留出空间给空单元格，保持网格结构 -->
                    <div :key="`${colIndex}-${rowIndex}-empty`" class="relative h-[74px]" v-if="cell === null"></div>
                    <div v-else :key="`${colIndex}-${rowIndex}-filled`" class="relative">
                      <div 
                        class="w-16 h-16 rounded-full flex items-center justify-center m-1 relative"
                        :class="{
                          'bg-red-500': cell.result === 'banker',
                          'bg-blue-500': cell.result === 'player',
                          'bg-green-500': cell.result === 'tie'
                        }"
                        :title="`轮次: ${cell.round_id}, 结果: ${formatResult(cell.result)}`"
                      >
                        <!-- 拐弯标记 -->
                        <div v-if="cell.dragon" class="absolute -right-2 -top-2 w-5 h-5 rounded-full bg-yellow-400 border-2 border-white flex items-center justify-center z-10">
                          <span class="text-white text-xs font-bold">↘</span>
                        </div>
                        
                        <div class="text-xs text-center line-height-1">
                          <div v-if="cell.bet_choice" class="text-white">{{ formatBetChoice(cell.bet_choice) }}</div>
                          <div v-if="cell.bet_amount > 0" class="text-white">¥{{ cell.bet_amount }}</div>
                          <div v-if="cell.bet_amount > 0" 
                            :class="{ 
                              'text-green-200': cell.win_or_lose === 1, 
                              'text-black font-bold': cell.win_or_lose === 0,
                              'text-white': cell.win_or_lose === 2
                            }"
                          >
                            {{ cell.win_or_lose === 1 ? '+' + cell.payout : 
                               cell.win_or_lose === 0 ? '-' + cell.bet_amount : '0' }}
                          </div>
                        </div>
                        
                        <!-- 轮次号 -->
                        <div class="absolute -top-1 -left-1 bg-gray-800 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                          {{ cell.round_id }}
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 返回顶部按钮 -->
    <button 
      v-show="showBackToTop" 
      @click="scrollToTop"
      class="fixed bottom-6 right-6 p-3 bg-blue-600 text-white rounded-full shadow-lg hover:bg-blue-700 transition-all z-50"
      title="返回顶部"
    >
      <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
      </svg>
    </button>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import api from '../logic/api'

export default {
  name: 'SimulationResultPage',
  props: {
    id: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      isLoading: true,
      error: null,
      summary: {},
      rounds: [],
      deckInfo: {},
      pageSize: 20,
      currentPage: 1,
      showAllCards: false,
      showBackToTop: false,
      chartsInitialized: false
    }
  },
  computed: {
    avgProfit() {
      if (!this.summary.total_rounds) return 0
      return (this.summary.net_profit / this.summary.total_rounds).toFixed(1)
    },
    totalPages() {
      return Math.ceil(this.rounds.length / this.pageSize)
    },
    displayedPages() {
      const pages = []
      for (let i = 1; i <= this.totalPages; i++) {
        pages.push(i)
      }
      return pages
    },
    paginatedRounds() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.rounds.slice(start, start + this.pageSize)
    },
    roadMap() {
      // 生成路图数据（大路），最多6行，第7个及以后向右拐弯显示
      if (!this.rounds.length) return []
      
      // 初始化二维网格结构，用于存储路图数据
      const grid = []
      for (let i = 0; i < 50; i++) {
        // 初始化每列为6个空位置（确保每列都有6行）
        grid[i] = Array(6).fill(null); 
      }
      
      let col = 0 // 当前列
      let row = 0 // 当前行
      let lastResult = null
      
      this.rounds.forEach(round => {
        const result = round.result
        
        if (lastResult === null) {
          // 第一局
          grid[col][row] = { ...round, dragon: false }
          lastResult = result
        } else if (result === lastResult) {
          // 结果连续，向下延伸，但最多6行
          if (row < 5) {
            // 正常向下延伸
            row++
            grid[col][row] = { ...round, dragon: false }
          } else {
            // 达到第6行，需要顺着第六行向右拐弯（保持在第6行）
            col++
            grid[col][5] = { ...round, dragon: true } // 标记为拐弯路线，确保在第6行(索引5)
          }
        } else {
          // 结果改变，新开一列
          col++
          row = 0
          grid[col][row] = { ...round, dragon: false }
          lastResult = result
        }
      })
      
      // 转换为紧凑格式，去除空列（但保留列内的null，以保持六行结构）
      const compactGrid = grid.filter(column => column.some(cell => cell !== null))
      
      return compactGrid
    }
  },
  async mounted() {
    await this.fetchSimulationData()
    if (!this.error) {
      // 延迟更长时间以确保DOM完全渲染
      setTimeout(() => {
        this.initCharts()
      }, 500)
    }
    
    // 监听滚动事件显示/隐藏返回顶部按钮
    window.addEventListener('scroll', this.handleScroll)
  },
  updated() {
    // 当组件更新时，如果有数据但图表还未初始化，再次尝试初始化
    this.$nextTick(() => {
      if (this.rounds.length > 0 && !this.chartsInitialized && !this.isLoading) {
        this.initCharts()
      }
    })
  },
  beforeDestroy() {
    // 销毁所有图表实例，避免内存泄漏
    if (this.$refs.profitChart) {
      echarts.dispose(this.$refs.profitChart)
    }
    if (this.$refs.roundProfitChart) {
      echarts.dispose(this.$refs.roundProfitChart)
    }
    if (this.$refs.resultPieChart) {
      echarts.dispose(this.$refs.resultPieChart)
    }
    if (this.$refs.betChoiceChart) {
      echarts.dispose(this.$refs.betChoiceChart)
    }
    
    // 移除滚动事件监听
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll() {
      // 滚动超过300px显示返回顶部按钮
      this.showBackToTop = window.scrollY > 300
    },
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    },
    async fetchSimulationData() {
      try {
        this.isLoading = true
        const data = await api.simulations.getById(this.id)
        this.summary = data.summary || {}
        this.rounds = data.rounds || []
        this.deckInfo = data.deck_info || {}
        
        // 确保牌组数据正确格式化
        if (this.deckInfo && this.deckInfo.deck_data) {
          console.log("原始牌组数据:", this.deckInfo.deck_data);
        }
        
        // 数据加载完成后，确保在下一个DOM更新周期尝试初始化图表
        this.$nextTick(() => {
          setTimeout(() => {
            if (!this.chartsInitialized) {
              this.initCharts();
            }
          }, 300);
        });
        
      } catch (error) {
        console.error('获取模拟数据错误', error)
        this.error = error.message
      } finally {
        this.isLoading = false
      }
    },
    
    initCharts() {
      console.log('初始化图表, DOM elements:', {
        profitChart: this.$refs.profitChart,
        roundProfitChart: this.$refs.roundProfitChart, 
        resultPieChart: this.$refs.resultPieChart,
        betChoiceChart: this.$refs.betChoiceChart
      })
      
      // 如果DOM元素都存在，则初始化图表
      if (this.$refs.profitChart && this.$refs.resultPieChart && this.$refs.betChoiceChart) {
        try {
          // 确保DOM元素存在后再初始化图表
          if (this.$refs.profitChart) {
            this.initProfitChart()
          } else {
            console.error('收益曲线DOM元素不存在')
          }
          
          if (this.$refs.roundProfitChart) {
            this.initRoundProfitChart()
          } else {
            console.error('单局输赢分析图表DOM元素不存在')
          }
          
          if (this.$refs.resultPieChart) {
            this.initResultPieChart()
          } else {
            console.error('游戏结果分布DOM元素不存在')
          }
          
          if (this.$refs.betChoiceChart) {
            this.initBetChoiceChart()
          } else {
            console.error('下注方向统计DOM元素不存在')
          }
          
          this.chartsInitialized = true
        } catch (error) {
          console.error('初始化图表失败:', error)
        }
      } else {
        console.warn('图表DOM元素尚未准备好，稍后将重试初始化')
        
        // 如果DOM元素不存在，则设置一个短暂的延迟后再次尝试
        setTimeout(() => {
          if (!this.chartsInitialized) {
            this.initCharts()
          }
        }, 300)
      }
    },
    
    initProfitChart() {
      if (!this.rounds.length) return
      
      // 获取DOM元素
      const chartDom = this.$refs.profitChart
      if (!chartDom) {
        console.error('收益曲线图表DOM元素不存在')
        return
      }
      
      try {
        // 先销毁可能存在的图表实例
        echarts.dispose(chartDom)
        
        // 计算累计收益数据
        const profitData = []
        let cumulativeProfit = 0
        
        this.rounds.forEach(round => {
          // 只有有下注的局才计算收益
          if (round.bet_amount > 0) {
            if (round.win_or_lose === 1) {  // 赢
              cumulativeProfit += round.payout
            } else if (round.win_or_lose === 0) {  // 输
              cumulativeProfit -= round.bet_amount
            }
            // win_or_lose === 2 (和局) 不影响收益
          }
          
          // 记录每局的累计收益 [轮次号, 累计收益]
          profitData.push([round.round_id, cumulativeProfit])
        })
        
        // 初始化图表
        const myChart = echarts.init(chartDom)
        
        const option = {
          title: {
            text: '收益曲线',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: function(params) {
              const data = params[0].data
              return `轮次: ${data[0]}<br/>累计收益: ${data[1] > 0 ? '+' : ''}${data[1]}`
            }
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '10%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            name: '轮次',
            min: 'dataMin'
          },
          yAxis: {
            type: 'value',
            name: '累计收益',
            axisLabel: {
              formatter: '{value}'
            }
          },
          series: [
            {
              name: '累计收益',
              type: 'line',
              data: profitData,
              showSymbol: true,
              symbolSize: 4,
              lineStyle: {
                width: 2,
                color: '#5470c6'
              },
              areaStyle: {
                opacity: 0.3,
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(84, 112, 198, 0.5)' },
                  { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
                ])
              },
              markLine: {
                silent: true,
                lineStyle: {
                  color: '#333',
                  type: 'dashed'
                },
                data: [
                  {
                    yAxis: 0,
                    label: {
                      position: 'start',
                      formatter: '盈亏平衡线'
                    }
                  }
                ]
              }
            }
          ]
        }
        
        // 设置图表
        myChart.setOption(option);
        console.log('收益曲线数据点数:', profitData.length);
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          if (myChart && !myChart.isDisposed()) {
            myChart.resize()
          }
        })
      } catch (error) {
        console.error('初始化收益曲线图表失败:', error)
      }
    },
    
    initResultPieChart() {
      if (!this.rounds.length) return
      
      // 获取DOM元素
      const chartDom = this.$refs.resultPieChart
      if (!chartDom) {
        console.error('游戏结果分布图表DOM元素不存在')
        return
      }
      
      try {
        // 先销毁可能存在的图表实例
        echarts.dispose(chartDom)
        
        // 统计游戏结果
        const resultCounts = {
          player: 0,
          banker: 0,
          tie: 0
        }
        
        this.rounds.forEach(round => {
          resultCounts[round.result]++
        })
        
        // 初始化结果分布饼图
        const myChart = echarts.init(chartDom)
        
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
          },
          legend: {
            orient: 'horizontal',
            bottom: 0
          },
          series: [
            {
              name: '游戏结果',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: 16,
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: [
                { 
                  value: resultCounts.player, 
                  name: '闲', 
                  itemStyle: { color: '#409EFF' } 
                },
                { 
                  value: resultCounts.banker, 
                  name: '庄', 
                  itemStyle: { color: '#F56C6C' } 
                },
                { 
                  value: resultCounts.tie, 
                  name: '和', 
                  itemStyle: { color: '#67C23A' } 
                }
              ]
            }
          ]
        }
        
        myChart.setOption(option)
        
        window.addEventListener('resize', () => {
          if (myChart && !myChart.isDisposed()) {
            myChart.resize()
          }
        })
      } catch (error) {
        console.error('初始化游戏结果分布图表失败:', error)
      }
    },
    
    initBetChoiceChart() {
      if (!this.rounds.length) return
      
      // 获取DOM元素
      const chartDom = this.$refs.betChoiceChart
      if (!chartDom) {
        console.error('下注方向统计图表DOM元素不存在')
        return
      }
      
      try {
        // 先销毁可能存在的图表实例
        echarts.dispose(chartDom)
        
        // 统计下注选择
        const betChoiceCounts = {
          player: 0,
          banker: 0,
          tie: 0,
          none: 0
        }
        
        this.rounds.forEach(round => {
          if (!round.bet_choice || round.bet_amount <= 0) {
            betChoiceCounts.none++
          } else {
            betChoiceCounts[round.bet_choice]++
          }
        })
        
        // 初始化下注选择柱状图
        const myChart = echarts.init(chartDom)
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['下注次数']
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: ['闲', '庄', '和', '未下注']
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              name: '下注次数',
              type: 'bar',
              itemStyle: {
                color: function(params) {
                  const colorList = ['#409EFF', '#F56C6C', '#67C23A', '#909399']
                  return colorList[params.dataIndex]
                }
              },
              data: [
                betChoiceCounts.player,
                betChoiceCounts.banker,
                betChoiceCounts.tie,
                betChoiceCounts.none
              ]
            }
          ]
        }
        
        myChart.setOption(option)
        
        window.addEventListener('resize', () => {
          if (myChart && !myChart.isDisposed()) {
            myChart.resize()
          }
        })
      } catch (error) {
        console.error('初始化下注方向统计图表失败:', error)
      }
    },
    
    initRoundProfitChart() {
      if (!this.rounds.length) return
      
      // 获取DOM元素
      const chartDom = this.$refs.roundProfitChart
      if (!chartDom) {
        console.error('单局输赢分析图表DOM元素不存在')
        return
      }
      
      try {
        // 先销毁可能存在的图表实例
        echarts.dispose(chartDom)
        
        // 计算每局的收益数据
        const profitData = []
        
        // 直接根据每局的输赢情况计算收益
        this.rounds.forEach(round => {
          let roundProfit = 0
          
          // 只处理有下注的局
          if (round.bet_amount > 0) {
            if (round.win_or_lose === 1) {
              // 赢了获得payout
              roundProfit = round.payout
            } else if (round.win_or_lose === 0) {
              // 输了扣除bet_amount
              roundProfit = -round.bet_amount
            }
            // win_or_lose === 2 (和局退回本金) 收益为0，不处理
          }
          
          // 添加数据点 [局号, 该局收益]
          profitData.push({
            value: [round.round_id, roundProfit],
            itemStyle: {
              color: roundProfit > 0 ? '#67C23A' : (roundProfit < 0 ? '#F56C6C' : '#909399')
            }
          })
        })
        
        // 初始化柱状图
        const myChart = echarts.init(chartDom)
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const data = params[0].data.value
              return `轮次: ${data[0]}<br/>收益: ${data[1] > 0 ? '+' : ''}${data[1]}`
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            name: '轮次',
            nameLocation: 'middle',
            nameGap: 30,
            axisLabel: {
              formatter: '{value}'
            }
          },
          yAxis: {
            type: 'value',
            name: '单局收益',
            nameLocation: 'middle',
            nameGap: 40,
            axisLine: {
              lineStyle: {
                color: '#999'
              }
            },
            splitLine: {
              lineStyle: {
                type: 'dashed',
                color: '#DDD'
              }
            }
          },
          dataZoom: [
            {
              type: 'inside',
              start: 0,
              end: 100
            },
            {
              start: 0,
              end: 100
            }
          ],
          series: [
            {
              name: '单局收益',
              type: 'bar',
              data: profitData
            }
          ]
        }
        
        myChart.setOption(option)
        
        // 响应窗口大小变化
        window.addEventListener('resize', () => {
          if (myChart && !myChart.isDisposed()) {
            myChart.resize()
          }
        })
      } catch (error) {
        console.error('初始化单局输赢分析图表失败:', error)
      }
    },
    
    getBetChoiceClass(betChoice) {
      if (betChoice === 'player') return 'text-blue-600 font-medium'
      if (betChoice === 'banker') return 'text-red-600 font-medium'
      if (betChoice === 'tie') return 'text-green-600 font-medium'
      return 'text-gray-500'
    },
    
    getResultClass(result) {
      if (result === 'player') return 'text-blue-600 font-medium'
      if (result === 'banker') return 'text-red-600 font-medium'
      if (result === 'tie') return 'text-green-600 font-medium'
      return 'text-gray-500'
    },
    
    getProfitClass(round) {
      if (round.bet_amount <= 0) return 'text-gray-400'
      return round.win_or_lose === 1 ? 'text-green-600' : (round.win_or_lose === 0 ? 'text-red-500' : 'text-gray-500')
    },
    
    getCardClass(card) {
      // 从卡片字符串中提取花色
      if (card.startsWith('♠')) return 'spade'
      if (card.startsWith('♥')) return 'heart'
      if (card.startsWith('♣')) return 'club'
      if (card.startsWith('♦')) return 'diamond'
      return ''
    },
    
    getCardDisplay(card) {
      // 提取花色和牌面值
      const suit = card.charAt(0);
      const value = card.substring(1);
      
      // 返回HTML格式的牌面显示
      return `${suit}<br>${value}`;
    },
    
    async clearSimulation() {
      if (!confirm(`确定要删除此模拟记录吗？此操作不可恢复。`)) {
        return
      }
      
      try {
        this.isLoading = true
        await api.simulations.clearById(this.id)
        alert(`模拟记录已删除`)
        // 跳转回结果列表页面
        this.$router.push('/results')
      } catch (error) {
        console.error('删除模拟记录失败', error)
        alert(`删除失败: ${error.message}`)
        this.isLoading = false
      }
    },
    
    formatCard(card) {
      // 确保card是字符串
      if (!card) return '';
      
      // 格式化牌面 (例如：将"♠A"格式化为"A")
      return card.substring(1);
    },
    
    getCardClassByString(card) {
      // 确保card是字符串
      if (!card) return '';
      
      // 从卡片字符串中提取花色
      if (card.startsWith('♠')) return 'spade';
      if (card.startsWith('♥')) return 'heart';
      if (card.startsWith('♣')) return 'club';
      if (card.startsWith('♦')) return 'diamond';
      return '';
    },
    
    formatResult(result) {
      if (result === 'player') return '闲赢'
      if (result === 'banker') return '庄赢'
      if (result === 'tie') return '和'
      return '未确定'
    },
    
    formatBetChoice(betChoice) {
      if (betChoice === 'player') return '闲'
      if (betChoice === 'banker') return '庄'
      if (betChoice === 'tie') return '和'
      return '未下注'
    }
  }
}
</script> 